package org.cainiao.servlet.workflow.service;

import lombok.RequiredArgsConstructor;
import org.cainiao.servlet.workflow.entity.Person;
import org.cainiao.servlet.workflow.repository.PersonRepository;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import static org.cainiao.servlet.workflow.entity.Person.Hobby;

@Service
@Transactional
@RequiredArgsConstructor
public class MyService {

    private final RuntimeService runtimeService;

    private final TaskService taskService;

    private final PersonRepository personRepository;

    public void startProcessByKey(String key) {
        Map<String, Object> variables = new HashMap<>();
        Person person = personRepository.findByUsername("jbarrez");
        List<Hobby> hobbies = new ArrayList<>();
        hobbies.add(new Hobby("painting"));
        hobbies.add(new Hobby("dance"));
        person.setHobbies(hobbies);
        variables.put("person", person);
        runtimeService.startProcessInstanceByKey(key, variables);
    }

    public void startProcess() {
        runtimeService.startProcessInstanceByKey("oneTaskProcess");
    }

    public void startProcess(String assignee) {
        Person person = personRepository.findByUsername(assignee);
        Map<String, Object> variables = new HashMap<>();
        variables.put("person", person);
        runtimeService.startProcessInstanceByKey("oneTaskProcess", variables);
    }

    public List<Task> getTasks(String assignee) {
        return taskService.createTaskQuery().taskAssignee(assignee).list();
    }

    public void createDemoUsers() {
        if (personRepository.findAll().size() == 0) {
            personRepository.save(new Person("jbarrez", "Joram", "Barrez", new Date()));
            personRepository.save(new Person("trademakers", "Tijs", "Rademakers", new Date()));
        }
    }
}
